#include "QtPcb.h"
#include "ui_QtPcb.h"
QtPcb::QtPcb(QWidget* parent)
    : QWidget(parent)
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);

    QHBoxLayout* inputLayout = new QHBoxLayout();
    idInput = new QLineEdit(this);
    timeInput = new QLineEdit(this);


    inputLayout->addWidget(new QLabel("ID:", this));
    inputLayout->addWidget(idInput);
    inputLayout->addWidget(new QLabel("Time:", this));
    inputLayout->addWidget(timeInput);


    QPushButton* addButton = new QPushButton("Add Process", this);
    connect(addButton, &QPushButton::clicked, this, &QtPcb::addProcessButton);

    QPushButton* startButtonPrio = new QPushButton("Start Priority Scheduling", this);
    connect(startButtonPrio, &QPushButton::clicked, this, &QtPcb::runButtonPrio);

    QPushButton* startButtonR = new QPushButton("Start Round Scheduling", this);
    connect(startButtonR, &QPushButton::clicked, this, &QtPcb::runButtonR);


    processListLayout = new QVBoxLayout();

    mainLayout->addLayout(inputLayout);
    mainLayout->addWidget(addButton);
    mainLayout->addWidget(startButtonPrio);
    mainLayout->addWidget(startButtonR);
    mainLayout->addLayout(processListLayout);

    animationGroup = new QSequentialAnimationGroup(this);
    connect(&scheduler, &Scheduler::processStarted, this, &QtPcb::handleProcessStarted);
    connect(&scheduler, &Scheduler::processFinished, this, &QtPcb::handleProcessFinished);
    connect(&scheduler, &Scheduler::processUpdated, this, &QtPcb::handleProcessUpdated);

}
   QtPcb::~QtPcb()
 {
 
}

void QtPcb::addProcessButton() {
    int id = idInput->text().toInt();
    int time = timeInput->text().toInt();

    scheduler.addProcess(id, time);

    ProcessWidget* processWidget = new ProcessWidget(id, this);
    processListLayout->addWidget(processWidget);
    processWidgets.insert(id, processWidget);
}
void QtPcb::runButtonPrio()
{
    scheduler.prioRun();
}

void QtPcb::runButtonR()
{
    scheduler.roundRun();
}

void QtPcb::handleProcessStarted(int id)
{
    ProcessWidget* widget = processWidgets.value(id);
    QPropertyAnimation* animation = new QPropertyAnimation(widget, "posX");
    animation->setDuration(1000);
    animation->setStartValue(0);
    animation->setEndValue(200);
    animationGroup->addAnimation(animation);
    animationGroup->start();
}

void QtPcb::handleProcessFinished(int id)
{
    ProcessWidget* widget = processWidgets.value(id);
    QPropertyAnimation* animation = new QPropertyAnimation(widget, "posX");
    animation->setDuration(1000);
    animation->setStartValue(200);
    animation->setEndValue(400);
    animationGroup->addAnimation(animation);
    animationGroup->start();
}


void QtPcb::handleProcessUpdated(int id, int remainingTime)
{
    ProcessWidget* widget = processWidgets.value(id);
    widget->setToolTip(QString("Remaining Time: %1").arg(remainingTime));
}



